<template>
  <div class="create">
    <el-drawer v-model="isVisible" :show-close="false" border>
      <div class="nav-container">
        <ul class="tab-list">
          <li
            class="tab"
            :class="{ active: activeTab === 1 }"
            to="/"
            @click="activeTab = 1"
          >
            新建班级
          </li>
          <li
            class="tab"
            :class="{ active: activeTab === 2 }"
            to="/teacher"
            @click="activeTab = 2"
          >
            加入已有
          </li>
        </ul>
        <div class="line" :style="{ left: changeLineLeft(activeTab) }"></div>
      </div>
      <el-form :model="formState" label-width="auto" ref="ruleFormRef">
        <el-form-item
          v-if="activeTab === 1"
          label="靶向班名称"
          prop="className"
          :rules="{
            required: true,
            message: '请输入靶向班名称'
          }"
        >
          <el-input
            v-model="formState.className"
            placeholder="请输入靶向班名称"
          />
        </el-form-item>
        <el-form-item
          v-else
          label="靶向班名称"
          prop="classId"
          :rules="{
            required: true,
            message: '请选择靶向班'
          }"
        >
          <Select v-model="formState.classId" :list="selectTargetList" />
        </el-form-item>
        <el-form-item
          label="靶向科目"
          prop="subject"
          :rules="{
            required: true,
            message: '请选择靶向科目'
          }"
        >
          <Select
            v-model="formState.subject"
            :list="selectSubjectList"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="目标" prop="target">
          <el-input
            v-model="formState.target"
            :rows="2"
            type="textarea"
            placeholder="请输入目标"
          />
        </el-form-item>
        <el-form-item>
          <div class="section">
            <div class="label">
              <span>选中的学生</span>
              <span class="light">（{{ studentListData.length }}）</span>
            </div>
            <ul class="student-list">
              <li
                class="student-item"
                v-for="item in studentListData"
                :key="item.key"
                @click="deleteStudent(index)"
              >
                <span>{{ item.studentName }}</span>
                <img
                  class="delete-icon"
                  src="@/assets/images/workbench/delete.png"
                />
              </li>
              <li class="error" v-if="isShowError">学生不能为空</li>
            </ul>
          </div>
        </el-form-item>
      </el-form>
      <div class="operation-container">
        <el-button @click="onCancel(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="onSubmit(ruleFormRef)"
          >确认</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, watch, computed } from 'vue'
import { reactive } from 'vue'
import {
  // getSubjectList,
  postAddTargetClass,
  postAddTargetClassStudent,
  getVisibleTargetClasses
} from '@/apis/workbench/class-manage/service'
import { postCollect } from '@/apis/assignment/index'
import { ElMessage } from 'element-plus'
import Select from './Select.vue'
import { useAuthStore } from '@/stores'

const props = defineProps({
  visible: { type: Boolean, default: false },
  studentList: { type: Array, default: () => [] },
  schoolId: { type: String, default: '' },
  teacherId: { type: String, default: '' },
  currentGrade: { type: [String, Number], default: '' }
})
const emit = defineEmits(['close'])

const authStore = useAuthStore()
const isVisible = ref(false)
const activeTab = ref(1)
const formState = reactive({
  className: '',
  classId: undefined,
  subject: '',
  target: ''
})
const ruleFormRef = ref(null)
const studentListData = ref([])
const subjectList = ref([])
const targetClassList = ref([])
const isShowError = ref(false)
const curGradeId = ref(0)

const selectTargetList = computed(() => {
  return targetClassList.value.map(item => ({
    label: item.targetName,
    value: item.targetClassId
  }))
})

// 改成用全局当前选中的科目并且不可切换
const selectSubjectList = computed(() => {
  const target = authStore.globalSubjectList.find(
    item => item.subject_num === authStore.nowGlobalSubjectId
  )
  return [
    {
      label: target.subject_name,
      value: target.subject_code
    }
  ]
  // return subjectList.value.map(item => ({
  //   label: item.subjectName,
  //   value: item.subjectCode
  // }))
})

watch(
  () => props.visible,
  async newVal => {
    if (newVal) {
      isVisible.value = props.visible
      studentListData.value = JSON.parse(JSON.stringify(props.studentList))
      await requestGetSubjectList()
      formState.subject = authStore.globalSubjectList.find(
        item => item.subject_num === authStore.nowGlobalSubjectId
      ).subject_code

      const gradeName = studentListData.value[0]?.gradeName || ''
      curGradeId.value = props.currentGrade
        ? props.currentGrade
        : studentListData.value[0]?.gradeId || 0
      const currentDate = new Date()
      let month = currentDate.getMonth() + 1
      month = month < 10 ? `0${month}` : month
      let day = currentDate.getDate()
      day = day < 10 ? `0${day}` : day
      const MMDD = `${month}${day}`
      formState.className = `${gradeName}靶向班${MMDD}`
    } else {
      isShowError.value = false
      activeTab.value = 1
    }
  }
)

watch(activeTab, newVal => {
  if (newVal === 2) {
    requestGetTargetClasses()
  } else {
    formState.subject = authStore.globalSubjectList.find(
      item => item.subject_num === authStore.nowGlobalSubjectId
    ).subject_code
    formState.target = undefined
    console.log(formState.subject, subjectList.value[0])
  }
})

watch(isVisible, newVal => {
  !newVal && emit('close')
})

watch(
  () => formState.classId,
  newVal => {
    if (newVal) {
      const index = targetClassList.value.findIndex(
        item => item.targetClassId === newVal
      )
      formState.subject = targetClassList.value[index].subjectCode
      formState.target = targetClassList.value[index].target
    }
  }
)

function changeLineLeft(activeTab) {
  switch (activeTab) {
    case 1:
      return '0.1rem'
    case 2:
      return '0.7rem'
  }
}

const deleteStudent = index => {
  studentListData.value.splice(index, 1)
}

const onCancel = formEl => {
  if (!formEl) return
  formEl.resetFields()
  isVisible.value = false
  emit('close')
}

/**
 * 创建靶向班
 */
const onSubmit = async formEl => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      if (!studentListData.value.length) {
        isShowError.value = true
        return
      }

      let targetClassId = 0
      if (activeTab.value === 1) {
        targetClassId = await createTargetClass()
      } else {
        targetClassId = formState.classId
      }
      const result = await postAddTargetClassStudent({
        school_id: Number(props.schoolId),
        class_id: targetClassId,
        student_ids: studentListData.value.map(student => Number(student.key))
      })
      if (result.msg === 'success') {
        formEl.resetFields()
        isVisible.value = false
        ElMessage.success(activeTab.value === 1 ? '创建成功' : '加入成功')
        emit('close', 'refresh')
      } else {
        ElMessage.error(result.msg)
      }
    } else {
      if (!studentListData.value.length) {
        isShowError.value = true
        return
      }
    }
  })
}

async function createTargetClass() {
  const res = await postAddTargetClass({
    school_id: Number(props.schoolId),
    class_name: formState.className,
    subject_code: formState.subject,
    target: formState.target,
    teacher_id: Number(props.teacherId),
    grade_id: Number(curGradeId.value)
  })

  if (res.msg === 'success' && res.data) {
    postCollect({
      action_type: 6
    })
    return res.data
  } else {
    ElMessage.error(res.msg)
  }
}

/**
 * 获取老师教的学科列表
 */
async function requestGetSubjectList() {
  if (!props.schoolId) {
    return
  }
  subjectList.value = authStore.globalSubjectList.map(v => ({
    subjectName: v.subject_name,
    subjectCode: v.subject_code
  }))
  // const res = await getSubjectList({
  //   teacher_ids: props.teacherId.toString()
  // })
  // let subjects = res.data[0].subjects || []
  // subjectList.value = subjects
  //   .filter(item => item.subject_name && item.subject_code)
  //   .map(item => {
  //     const { subject_name, subject_code } = item
  //     return {
  //       subjectName: subject_name,
  //       subjectCode: subject_code
  //     }
  //   })
}

/**
 * 获取可见的靶向班列表
 */
async function requestGetTargetClasses() {
  const { data } = await getVisibleTargetClasses({
    school_id: Number(props.schoolId),
    teacher_id: Number(props.teacherId)
  })
  const list = data?.list || []
  targetClassList.value = list.map(item => ({
    targetName: item.name,
    targetClassId: item.class_id,
    subjectCode: item.subject_code,
    target: item.target
  }))
  formState.classId = targetClassList.value[0]?.targetClassId || undefined
}
</script>
<style lang="less" scoped>
.create {
  :deep(.el-drawer) {
    width: 729px;
    box-sizing: border-box;
    padding: 25px 40px;

    &__header {
      display: none;
    }

    &__body {
      padding: unset;
      display: flex;
      flex-direction: column;
      gap: 36px;
      justify-content: space-between;
    }
  }

  .nav-container {
    position: relative;

    .tab-list {
      display: flex;
      align-items: center;

      .tab {
        width: 84px;
        height: 30px;
        font-weight: bold;
        font-size: @size-nav1;
        color: @color-neutral-title-darker;
        opacity: 0.3;
        margin-right: 35px;
        cursor: pointer;
        text-align: center;

        &:last-child {
          margin-right: 0;
        }
      }

      .active {
        color: @color-brand-regular;
        opacity: 1;
      }
    }

    .line {
      position: absolute;
      bottom: -13px;
      width: 54px;
      height: 8px;
      border-radius: 8px;
      transition: 0.3s;
      background: url('@/assets/images/login/active-line.svg') no-repeat center
        center/100% 100%;
      background-size: contain;
    }
  }

  :deep(.el-form) {
    flex: 1;
    overflow: auto;

    .el-form-item {
      flex-direction: column;

      .el-form-item__label-wrap,
      .el-form-item__content {
        margin-left: 0 !important;
      }

      .el-form-item__label-wrap > .el-form-item__label {
        font-weight: 500;
        font-size: @size-nav2;
        color: @color-neutral-title-darker;
        opacity: 0.9;
        margin-bottom: 8px;
      }

      .el-input {
        width: 645px;
        height: 40px;
      }

      .el-input__wrapper {
        height: 100%;
        box-shadow: 0 0 0 1px #9bc3ff inset;
        border-radius: 5px;
        font-size: @size-nav4;

        .el-input__inner {
          color: rgba(4, 11, 26, 0.4);
          font-size: @size-nav4;
        }

        .el-input__inner::placeholder,
        .el-input__prefix {
          color: @color-neutral-title-darker;
          opacity: 0.3;
        }
      }

      .el-textarea {
        width: 645px;
        height: 98px;

        .el-textarea__inner {
          height: 100%;
          box-shadow: 0 0 0 1px #9bc3ff inset;
          border-radius: @radius-component;
          font-size: @size-nav4;
          color: rgba(4, 11, 26, 0.4);

          &::placeholder {
            color: @color-neutral-title-darker;
            opacity: 0.3;
          }
        }
      }
    }
  }

  .operation-container {
    margin-top: auto;
    text-align: center;

    .el-button {
      width: 140px;
      height: 47px;
      border-radius: 4px;
      font-weight: bold;
      font-size: 20px;
      border: 1px solid @color-brand-regular;
      color: @color-brand-regular;
      margin-right: 35px;
    }

    .el-button--primary {
      background: @color-brand-regular;
      color: #fff;
      border: none;
    }
  }

  .section {
    margin-bottom: 19px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      font-weight: 500;
      font-size: @size-nav2;
      color: @color-neutral-title-darker;
      opacity: 0.9;
      margin-bottom: 8px;

      .light {
        color: @color-brand-regular;
      }
    }

    .student-list {
      position: relative;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 15px;

      .student-item {
        display: inline-block;
        height: 31px;
        padding: 0 14px;
        border-radius: 3px;
        border: 1px solid #9bc3ff;
        font-weight: 500;
        font-size: @size-nav4;
        color: #9bc3ff;
        cursor: pointer;

        .delete-icon {
          margin-left: 16px;
          width: 10px;
        }
      }

      .error {
        color: rgb(245 108 108);
        font-size: 0.0625rem;
        left: 0;
        position: absolute;
        top: 100%;
      }
    }
  }
}
</style>
